﻿var sessions = {};
var key = "session_id";
var EXPIRES = 20 * 60 * 1000;
var generate = function () {
    var session = {};
    session.id = (new Date()).getTime() + Math.random();
    session.cookie = {
        expires: (new Date()).getTime() + EXPIRES
    };
    sessions[session.id] = session;
    return session;
}


var handle = function (req, res) {
    if (!req.session.isVisit) {
        req.session.isVisit = true;
        res.writehead(200);
        res.end("first");
    } else {
        res.writehead(200);
        res.end("not first");
    }
}

function do1(req,res){
    var id = req.cookies[key];
    if (!id) {
        req.session = generate();
    } else {
        var session = sessions[id];
        if (session) {
            if (session.cookie.expire > (new Date()).getTime()) {
                session.cookie.expire = (new Date()).getTime() + EXPIRES;
                req.session = session;
            } else {
                //超时,删除旧的数据,并重新生成
                delete sessions[id];
                req.session = generate();
            }
        } else {
            //session 过期或者口令不对,重新生成session
            req.session = generate();
        }
    }
    handle(req,res);
}



exports.do1 = do1;